package br.com.NoTraffic.view;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;

import javax.comm.CommPortIdentifier;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import br.com.NoTraffic.acceptance.StringBuilder;
import br.com.NoTraffic.com.SComm;
import br.com.NoTraffic.util.MyTable;

public class TestWindow extends javax.swing.JFrame {
	private static final long serialVersionUID = 1L;

	private Icon icon;
	private JPanel jPanel1;
	private JLabel lblStatus;
	private JScrollPane jScrollPane1;
	private JButton btnStart;
	private JButton btnStop;
	private JPanel jPanel3;
	private MyTable tblVars;
	private JPanel jPanel2;
	private TableModel tblVarsModel;
	private JLabel lblBox;
	private JComboBox boxPortas;
	private String actualPort = "COM1";
	private SComm com;
	private Thread t;
	private boolean threadAlive = false;
	private boolean threadBusy = true;
	private String[] portas;

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				TestWindow inst = new TestWindow();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}

	public TestWindow() {
		super();
		icon = new ImageIcon("res/car.JPG");
		mapeatePorts();
		com = new SComm();
		msgSendingThread();
		initGUI();
		setTblVariaveis("Disconnected");

	}

	private void initGUI() {
		try {
			BorderLayout thisLayout = new BorderLayout();
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setTitle("No Traffic - Serial Comunication");
			getContentPane().setLayout(thisLayout);
			{
				jPanel1 = new JPanel();
				BorderLayout jPanel1Layout = new BorderLayout();
				getContentPane().add(jPanel1, BorderLayout.CENTER);
				jPanel1.setLayout(jPanel1Layout);
				{
					jScrollPane1 = new JScrollPane();
					jPanel1.add(jScrollPane1, BorderLayout.CENTER);
					{
						tblVarsModel = new DefaultTableModel(new String[][] {},
								new String[] { "Status" });
						tblVars = new MyTable();
						jScrollPane1.setViewportView(tblVars);
						tblVars.setModel(tblVarsModel);
					}
				}
			}
			{
				jPanel2 = new JPanel();
				getContentPane().add(jPanel2, BorderLayout.SOUTH);
				jPanel2.setPreferredSize(new java.awt.Dimension(392, 30));
				jPanel2.setLayout(null);
				{
					lblStatus = new JLabel(icon);
					jPanel2.add(lblStatus);
					lblStatus.setText("No Traffic corp. / All Rights Reserved");
					lblStatus.setBounds(12, 0, 300, 30);
				}
			}
			{
				jPanel3 = new JPanel();
				jPanel3.setLayout(null);
				getContentPane().add(jPanel3, BorderLayout.NORTH);
				jPanel3.setPreferredSize(new java.awt.Dimension(392, 38));
				{
					btnStart = new JButton();
					jPanel3.add(btnStart);
					btnStart.setText("Initiate");
					btnStart.setLayout(null);
					btnStart.setBounds(12, 10, 60, 21);

					btnStart.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							initiateCom(evt);
						}
					});

				}
				{
					btnStop = new JButton();
					jPanel3.add(btnStop);
					btnStop.setText("Stop");
					btnStop.setLayout(null);
					btnStop.setBounds(82, 10, 60, 21);
					btnStop.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							stopCom(evt);
						}
					});
				}
				{
					lblBox = new JLabel("Ports:");
					jPanel3.add(lblBox);
					lblBox.setBounds(212, 10, 112, 21);
					lblBox.setLayout(null);

					boxPortas = new JComboBox(portas);
					jPanel3.add(boxPortas);
					boxPortas.setLayout(null);
					boxPortas.setBounds(270, 10, 112, 21);

					boxPortas.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							setPort(evt);
						}
					});
				}
			}
			pack();
			setSize(400, 150);
			this.setLocationRelativeTo(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void stopCom(ActionEvent evt) {
		if (threadAlive && !threadBusy) {
			com.FecharCom();
			threadAlive = false;
			setTblVariaveis("Disconnected");
		}
	}

	protected void setPort(ActionEvent evt) {
		actualPort = (String) boxPortas.getSelectedItem();
	}

	protected void initiateCom(ActionEvent evt) {
		if (!threadAlive) {
			if (actualPort != null && actualPort.contains("COM")) {
				com = new SComm(actualPort, 9600, 1500);
				com.AbrirPorta();
				threadAlive = true;
				setTblVariaveis("Connected");
			} else {
				setTblVariaveis("Invalid Port");
			}
		}
	}

	protected void sendMessage(String msg) {
		if (threadAlive) {
			try {
				threadBusy = true;
				com.SendFrame(msg.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} finally {
				threadBusy = false;
			}
		}
	}

	public void setTblVariaveis(String status) {
		String[][] data = new String[1][1];
		data[0][0] = status;
		tblVarsModel = new DefaultTableModel(data, new String[] { "Status" });
		tblVars.setModel(tblVarsModel);
		tblVars.updateUI();
	}

	public void mapeatePorts() {
		Enumeration listaDePortas = CommPortIdentifier.getPortIdentifiers();
		int i = 0;
		portas = new String[10];
		while (listaDePortas.hasMoreElements()) {
			CommPortIdentifier ips = (CommPortIdentifier) listaDePortas
					.nextElement();
			portas[i] = ips.getName();
			i++;
		}
	}

	public void msgSendingThread() {
		t = new Thread(new Runnable() {
			String msg;

			public void run() {
				if (threadAlive) {
					try {
						msg = StringBuilder.getMessageFromZone('1');
						System.out.println(msg);
						sendMessage(msg);
						Thread.sleep(1000);

						msg = StringBuilder.getMessageFromZone('2');
						System.out.println(msg);
						sendMessage(msg);
						Thread.sleep(1000);

						msg = StringBuilder.getMessageFromZone('3');
						System.out.println(msg);
						sendMessage(msg);
						Thread.sleep(1000);

						msg = StringBuilder.getMessageFromZone('4');
						System.out.println(msg);
						sendMessage(msg);
						Thread.sleep(4000);

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				t = new Thread(this);
				t.start();
			}
		});
		t.start();
	}
}
